package com.jiexinyun.service.android.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jiexinyun.dao.RytreeMapper;
import com.jiexinyun.dto.request.androidwork.AndroidLoginReq;
import com.jiexinyun.dto.request.androidwork.AndroidLogoutReq;
import com.jiexinyun.dto.response.AjaxResult;
import com.jiexinyun.entity.RytreeEntity;
import com.jiexinyun.service.android.PublicWorkService;
import com.jiexinyun.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;

@Slf4j
@Service
public class PublicWorkServiceImpl implements PublicWorkService {

    @Autowired
    private RytreeMapper rytreeMapper;

    @Override
    public AjaxResult login(AndroidLoginReq req) {

        log.info("安卓端登录:{}", req);
        //不做那么麻烦，只做数据查询，验证员工编号，员工编号数据在万思表 rytree 表中，返回给安卓
        String ry_code = req.getRy_code();
        //查询员工编号对应的员工信息
        LambdaQueryWrapper<RytreeEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RytreeEntity::getRy_code, ry_code);
        List<RytreeEntity> list = rytreeMapper.selectList(lambdaQueryWrapper);

        //万思数据不值得相信，所以判断存在就可以了，不需要判断唯一性
        if(CommonUtils.isEmpty(list)) {
            return AjaxResult.error(ry_code+"员工牌不正确");
        }

        if(list.size() > 1) {
            return AjaxResult.error("员工牌编号有重复，请去万思修正，务必做到一个员工编号对应一人");
        }

        RytreeEntity rytreeEntity = list.get(0);

        Timestamp currentTime = Timestamp.from(Instant.now());

        rytreeEntity.setLast_login_time(currentTime);

        try {
            rytreeMapper.updateById(rytreeEntity);
        } catch (Exception e) {
            log.error("更新登录时间失败", e);
        }
        //代码走到这，就算是成功了，不做什么token了
        log.info("安卓端登录成功");
        return AjaxResult.success(rytreeEntity);
    }

    @Override
    public AjaxResult logout(AndroidLogoutReq req) {

        log.info("安卓端登出成功:{}", req);

        return AjaxResult.success();
    }
}
